import { Modal } from 'ant-design-vue'
import GoodsUnitTypeModal from '@/components/business/goods-unit-type-modal/index.vue'
export const useTransformSpec = () => {
  // 获取当前规格的数量
  function getSpecQuantity(quantity: number, spec: any) {
    if (!spec.conversion_rate) return 0
    if (spec.conversion_rate === 1) return quantity
    return Math.trunc(quantity / spec.conversion_rate)
  }

  // 获取最小单位的数量
  function getMinSpecQuantity(quantity: number, conversion_rate: number) {
    if (isNaN(quantity) || isNaN(conversion_rate)) return 0
    return quantity * conversion_rate
  }

  // 根据数量和specs中的conversion_rate依次求余
  function transformSpec(quantity: number, specs: any[]) {
    if (quantity === 0) return quantity
    if (!specs.length) return quantity
    let result = ''
    // 剩余数量
    let remainder = quantity
    for (const item of specs) {
      // 计算当前单位数量
      const num = getSpecQuantity(remainder, item)
      if (num === 0) continue
      result += `${num}${item.unit_name}`
      // 计算剩余数量
      remainder -= getMinSpecQuantity(num, item.conversion_rate)
      // 如果为0则结束循环
      if (remainder === 0) break
    }
    return result
  }

  // 规格计算Modal
  function openModal(quantity: number, specs: any[]): Promise<any> {
    return new Promise((resolve, reject) => {
      let result = 0
      Modal.confirm({
        icon: null,
        title: '规格计算',
        content: () => {
          return h(GoodsUnitTypeModal, {
            quantity,
            specs,
            result,
            'onUpdate:result': (val: number) => {
              result = val
            }
          })
        },
        onOk: () => {
          return resolve(result)
        },
        onCancel: () => {
          reject('cancel')
        }
      })
    })
  }
  return {
    getSpecQuantity,
    getMinSpecQuantity,
    transformSpec,
    openModal
  }
}
